package com.topvision.camerasdk;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.joanzapata.pdfview.PDFView;
import com.joanzapata.pdfview.listener.OnDrawListener;
import com.joanzapata.pdfview.listener.OnLoadCompleteListener;
import com.joanzapata.pdfview.listener.OnPageChangeListener;
import com.squareup.picasso.Picasso;
import com.topvision.camerasdk.album.ShowPicActivity;
import com.topvision.camerasdk.album.view.PhotoView;
import com.topvision.commomsdk.TouchInterface;
import com.topvision.commomsdk.constants.TvConstants;
import com.topvision.commomsdk.settings.BlueToothUtil;
import com.topvision.commomsdk.uitl.DocConversionUtil;
import com.topvision.voicesdk.BaseVoiceActivity;
import com.topvision.voicesdk.CommonVoice;
import com.topvision.voicesdk.VoiceInterface;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import okhttp3.Call;
import okhttp3.Response;


/**
 * The type Document activity.
 */
public class DocumentActivity extends BaseVoiceActivity implements TouchInterface, VoiceInterface, OnPageChangeListener, OnLoadCompleteListener, OnDrawListener {

    public static final String MICROSOFT_URL = "https://view.officeapps.live.com/op/view.aspx?src=";
    public String STR_SDCARD = "/mnt/sdcard/";
    public String PUSH_FILE_PATH = STR_SDCARD + "Zk/Html/";
    private WebView mWebView;
    //文件 类型
    private String fileType;
    //文件路径
    private String filePath;
    //html默认保存路径
    public String savePath = PUSH_FILE_PATH;
    // 文档工具类对象
    private DocConversionUtil documentUtil;
    private String htmlPath;
    private PDFView pdfView;
    private RelativeLayout filePdfRel, fileWordRel;
    private String url;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //此方法webview作为系统应用会报错
        hookWebView();
        setContentView(R.layout.activity_document);
        //如果有这个参数传入就自定义保存html路径 没有则默认
        htmlPath = getIntent().getStringExtra(DocConversionUtil.HTML_SAVE_PATH);
        filePath = getIntent().getStringExtra(DocConversionUtil.DOC_FILE_PATH);
        initView();
        initData();
        registerMyBroadcast();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTouchInterfaceListener(this);
        setVoiceInterfaceListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        setTouchInterfaceListener(null);
        setVoiceInterfaceListener(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterMyReceiver();
    }

    /**
     * Init view.
     */
    void initView() {

        mWebView = (WebView) findViewById(R.id.my_webview);
        pdfView = (PDFView) findViewById(R.id.file_pdf);
        filePdfRel = (RelativeLayout) findViewById(R.id.pdf_file_rel);
        fileWordRel = (RelativeLayout) findViewById(R.id.word_file_rel);
    }

    /**
     * Init data.
     */
    void initData() {
        if (!TextUtils.isEmpty(filePath)) {
            file = new File(filePath);
            //判断文件是否存在
            if (file.exists()) {
                String[] split = file.getName().split("\\.");
                fileType = split[1];
                if (!TextUtils.isEmpty(fileType)) {
                    if (fileType.equals(DocConversionUtil.DOC_TYPE)) {
                        readWord();
                    } else if (fileType.equals(DocConversionUtil.PDF_TYPE)) {
                        readPdf();
                    } else if (fileType.equals(DocConversionUtil.XLS_TYPE)) {
                        readExcel();
                    } else if (fileType.equals(DocConversionUtil.IMAGE_JPG_TYPE) || fileType.equals(DocConversionUtil.IMAGE_PNG_TYPE)) {
                        readImage();
                    }
                }

            }

        }
    }


    private void readWord() {
        if (TextUtils.isEmpty(htmlPath)) {
            htmlPath = savePath;
        }
        documentUtil = new DocConversionUtil(filePath, htmlPath);
        try {
            url = documentUtil.convert2Html();
            if (url.endsWith(".html")) {
                url = "file://" + url;
                fileWordRel.setVisibility(View.VISIBLE);
                previewFile();
            } else {
                Toast.makeText(this, "wordurl无效", Toast.LENGTH_LONG).show();
            }
        } catch (TransformerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();

        }

    }

    private void readPdf() {
        displayFromFile(file);
        filePdfRel.setVisibility(View.VISIBLE);
    }


    /**
     * Open document view.
     * 预览WORD文档
     */
    void previewFile() {
        WebSettings webSettings = mWebView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        //WebView加载web资源
        mWebView.loadUrl(url);
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
    }

    //预览PDF文档
    private void displayFromFile(File file) {
        pdfView.fromFile(file) // 设置pdf文件地址
                .defaultPage(1) // 设置默认显示第1页
                .onPageChange(this) // 设置翻页监听
                .onLoad(this) // 设置加载监听
                .onDraw(this) // 绘图监听
                .showMinimap(false) // pdf放大的时候，是否在屏幕的右上角生成小地图
                // .swipeVertical( false ) //pdf文档翻页是否是垂直翻页，默认是左右滑动翻页
                .enableSwipe(true) // 是否允许翻页，默认是允许翻
                // .pages( 2 , 3 , 4 , 5 ) //把2 , 3 , 4 , 5 过滤掉
                .load();
    }

    //加载监听  OnPageChangeListener
    @Override
    public void onPageChanged(int i, int i1) {

    }

    //加载监听  OnLoadCompleteListener
    @Override
    public void loadComplete(int i) {

    }

    //绘图监听  OnDrawListener
    @Override
    public void onLayerDrawn(Canvas canvas, float v, float v1, int i) {

    }

    //上传Excel表到服务器
    public void readExcel() {
        fileWordRel.setVisibility(View.VISIBLE);
        String btMac = BlueToothUtil.getBtMacNoColons(this);
        final String fileUrl = MICROSOFT_URL + TvConstants.BASE_IP + "/topvisionupload/backup/" + btMac + "/file/" + file.getName();
        // 文件上传
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        //将btMac信息传入后台
        postFormBuilder.addParams("guid", btMac);
        postFormBuilder.addFile("file", file.getName(), file); // 增加addFile可以多文件上传
        postFormBuilder
                .url(TvConstants.BASE_URL + "backups.do")
                .build()
                .execute(new Callback<File>() {
                    @Override
                    public void inProgress(float progress) {

                    }

                    @Override
                    public File parseNetworkResponse(Response response) throws Exception {
                        return null;
                    }

                    @Override
                    public void onError(Call arg0, Exception arg1) {
                        System.out.println("上传失败");
                        mhandler.sendEmptyMessage(2);
                    }

                    @Override
                    public void onResponse(File arg0) {
                        System.out.println("上传成功");
                        url = fileUrl;
                        mhandler.sendEmptyMessage(1);

                    }

                });


    }


    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    previewFile();
                    break;
                case 2:
                    //上传失败操作
                    break;
            }
        }
    };

    @Override
    public void doForwardTouch() {

    }

    @Override
    public void doBackwardTouch() {

    }

    @Override
    public void doClickTouch() {

    }

    @Override
    public void doDoubleTouch() {

    }

    @Override
    public void dealWithVoice(String data) {
        if (data.equals(CommonVoice.VOICE_ZH_BACK) || data.equalsIgnoreCase(CommonVoice.VOICE_US_BACK)) {
            finish();
        }
    }

    PhotoView photoView;

    /**
     * 读取图片信息
     * create at 2017/1/16 9:43
     */
    private void readImage() {
        photoView = (PhotoView) findViewById(R.id.file_img_iv);
        photoView.setVisibility(View.VISIBLE);
        //允许放大缩小
        photoView.enable();
//        photoView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        Picasso.with(this)
                .load(file)
                .into(photoView);
    }


    private void registerMyBroadcast() {
        if (myReceiver == null) {
            myReceiver = new MyReceiver();

        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ShowPicActivity.MyReceiver.ACTION_FINISH_ACTIVITY);
        registerReceiver(myReceiver, intentFilter);
    }

    private void unRegisterMyReceiver() {
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }


    MyReceiver myReceiver;

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ShowPicActivity.MyReceiver.ACTION_FINISH_ACTIVITY.equals(action)) {
                finish();
            }
        }
    }

    private void hookWebView() {
        Class<?> factoryClass = null;
        try {
            factoryClass = Class.forName("android.webkit.WebViewFactory");
            Method getProviderClassMethod = null;
            Object sProviderInstance = null;

            if (Build.VERSION.SDK_INT == 23) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
                getProviderClassMethod.setAccessible(true);
                Class<?> providerClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
                Class<?> delegateClass = Class.forName("android.webkit.WebViewDelegate");
                Constructor<?> constructor = providerClass.getConstructor(delegateClass);
                if (constructor != null) {
                    constructor.setAccessible(true);
                    Constructor<?> constructor2 = delegateClass.getDeclaredConstructor();
                    constructor2.setAccessible(true);
                    sProviderInstance = constructor.newInstance(constructor2.newInstance());
                }
            } else if (Build.VERSION.SDK_INT == 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
                getProviderClassMethod.setAccessible(true);
                Class<?> providerClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
                Class<?> delegateClass = Class.forName("android.webkit.WebViewDelegate");
                Constructor<?> constructor = providerClass.getConstructor(delegateClass);
                if (constructor != null) {
                    constructor.setAccessible(true);
                    Constructor<?> constructor2 = delegateClass.getDeclaredConstructor();
                    constructor2.setAccessible(true);
                    sProviderInstance = constructor.newInstance(constructor2.newInstance());
                }
            } else if (Build.VERSION.SDK_INT == 21) {//Android 21无WebView安全限制
                getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
                getProviderClassMethod.setAccessible(true);
                Class<?> providerClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
                sProviderInstance = providerClass.newInstance();
            }
            if (sProviderInstance != null) {
                Log.i("cym", sProviderInstance.toString());
                Field field = factoryClass.getDeclaredField("sProviderInstance");
                field.setAccessible(true);
                field.set("sProviderInstance", sProviderInstance);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
